package com.mengchengnet.chaperonage.adapter;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mengchengnet.chaperonage.R;
import com.mengchengnet.chaperonage.domain.base.Order;
import com.mengchengnet.chaperonage.ui.activity.RatingActivity;
import com.mengchengnet.chaperonage.util.PreferenceUtil;
import com.mengchengnet.chaperonage.util.Url;
import com.mengchengnet.chaperonage.util.ViewUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 16-2-22.
 */
public class OrderAdapter extends ArrayAdapter<Order> {

    private static final String TAG = "ChaperonageAdapter";
    private Context mContext;
    private int resourceId;
    private RequestQueue requestQueue;

    public OrderAdapter(Context context, int resource, List<Order> objects) {
        super(context, resource, objects);
        resourceId = resource;
        mContext = context;
        requestQueue= Volley.newRequestQueue(context);

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        final Order order = getItem(position); // 获取当前项的实例
        View view = LayoutInflater.from(getContext()).inflate(resourceId, null);

        ImageView imageView = (ImageView) view.findViewById(R.id.iv_photo);
        ViewUtil.showImageView(mContext, imageView, order.getChaperonagePhoto());

        TextView tvName = (TextView) view.findViewById(R.id.tv_name);
        tvName.setText(order.getBusinessType() + "-" + order.getChaperonageName());

        TextView tvState = (TextView) view.findViewById(R.id.tv_state);
        tvState.setText(order.getOrderState());

        TextView tvPrice = (TextView) view.findViewById(R.id.tv_price);
        tvPrice.setText(order.getPrice());

        TextView tvTotalPrice = (TextView) view.findViewById(R.id.tv_total_price);
        tvTotalPrice.setText(order.getTotalPrice());

        TextView tvServeTime = (TextView) view.findViewById(R.id.tv_serve_time);
        tvServeTime.setText(order.getServeTime());

        Button btn_cancel= (Button) view.findViewById(R.id.cancel_order);
        Button btn_tips= (Button) view.findViewById(R.id.tips);


        if (order.getOrderState().equals("待接单")){
            btn_tips.setVisibility(View.VISIBLE);
            btn_tips.setText("待接单");
            btn_cancel.setVisibility(View.VISIBLE);

        }else if(order.getOrderState().equals("待评价")){
            btn_tips.setVisibility(View.VISIBLE);
            btn_tips.setText("评价");
            btn_tips.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent =new Intent();
                    intent.putExtra("careId",order.getUserId());
                    intent.setClass(getContext(), RatingActivity.class);
                    getContext().startActivity(intent);
                }
            });
        }else if(order.getOrderState().equals("待服务")){
            btn_tips.setVisibility(View.VISIBLE);
            btn_tips.setText("待服务");

        }else if(order.getOrderState().equals("已完成")){
            btn_tips.setVisibility(View.VISIBLE);
            btn_tips.setText("已完成");
            btn_cancel.setVisibility(View.GONE);

        }else if(order.getOrderState().equals("待付款")){
            btn_tips.setVisibility(View.VISIBLE);
            btn_tips.setText("待付款");
            btn_cancel.setVisibility(View.GONE);

        }else if(order.getOrderState().equals("已结单")){
            btn_tips.setVisibility(View.GONE);
            btn_cancel.setVisibility(View.GONE);
        }
        //取消订单
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancelOrder(order.getOrderId());
            }
        });
        return view;
    }


    /**
     * 取消订单
     * @param orderId
     */
    private void cancelOrder(final String orderId) {
        StringRequest request = new StringRequest(Request.Method.POST, Url.cancel,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        Log.e(TAG, "取消订单: "+result );
                        JSONObject jsonObject;
                        try {
                            if(result != null && result.startsWith("\ufeff"))
                            {
                                result =  result.substring(1);
                            }

                            jsonObject = new JSONObject(result);
                            if (jsonObject.getString("code").equals("00")){
                                Toast.makeText(mContext, "订单已取消！", Toast.LENGTH_SHORT).show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("loginId",PreferenceUtil.getString(getContext(),"userId"));//接单人id
                Log.e(TAG, "订单id: "+orderId );
                map.put("item_id", orderId);//订单id
                Log.e(TAG, "接单人id: "+PreferenceUtil.getString(getContext(),"userId") );
                return map;
            }
        };
        request.setTag("GetFenZu");
        request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, // 默认超时时间，应设置一个稍微大点儿的
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 默认最大尝试次数
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(request);

    }


}
